package com.choichumgming.rentcat.service.Impl;

import com.choichumgming.rentcat.common.api.CommonResult;
import com.choichumgming.rentcat.component.CancelOrderSender;
import com.choichumgming.rentcat.dao.OrderReturnParamDao;
import com.choichumgming.rentcat.dto.OrderParam;
import com.choichumgming.rentcat.dto.OrderReturnParam;
import com.choichumgming.rentcat.mapper.*;
import com.choichumgming.rentcat.model.*;
import com.choichumgming.rentcat.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;


/**
 * @ClassName OmsBuyerOrderServiceImpl
 * @Description : 买家家订单Service
 * @Author : choichumgming
 * @Date : 5/3/2020 16:58
*/
@Slf4j
@Service
public class OmsBuyerOrderServiceImpl implements OmsBuyerOrderService {
    @Resource
    private UmsMemberFeignApi memberFeignApi;
    @Resource
    private UmsMemberReceiveAddressFeignApi memberReceiveAddressFeignApi;
    @Resource
    private PmsProductFeignApi pmsProductFeignApi;

    @Autowired
    private RedisService redisService;

    @Value("${redis.key.prefix.orderId}")
    private String REDIS_KEY_PREFIX_ORDER_ID;

    @Autowired
    private OmsOrderSettingMapper orderSettingMapper;

    @Autowired
    private OmsOrderItemMapper orderItemMapper;

    @Autowired
    private OmsOrderMapper orderMapper;

    @Autowired
    private OrderReturnParamDao orderReturnParamDao;

    @Autowired
    private CancelOrderSender cancelOrderSender;




    /**
     * 根据提交信息生成订单
     */
    @Override
    public CommonResult generateOrder(OrderParam orderParam) {
        log.warn(orderParam.toString());
        //生成下单订单信息
        OmsOrderItem orderItem = new OmsOrderItem();
        OmsOrder order = this.insertOrder( orderParam);
        orderItem.setOrderId(order.getOrderId());
        orderItem.setOrderSn(order.getOrderSn());
        orderItem.setStartTime(orderParam.getStartTime());
        orderItem.setEndTime(orderParam.getEndTime());
        orderItem.setFreightAmount(orderParam.getFreightAmount());
        orderItem.setPayAmount(orderParam.getPayAmount());
        orderItem.setTotalAmount(orderParam.getTotalAmount());

//        商品信息
        orderItem.setProductId(orderParam.getProductId());
        PmsProduct pmsProduct = pmsProductFeignApi.getProduct(orderParam.getProductId()).getData();
        orderItem.setProductName(pmsProduct.getName());
        orderItem.setProductPic(pmsProduct.getPic());
        orderItem.setProductPrice(pmsProduct.getPrice());
        orderItem.setProductCategoryId(pmsProduct.getProductCategoryId());
        orderItem.setProductCategoryName(pmsProduct.getProductCategoryName());

//

         orderItemMapper.insert(orderItem);

        //发送延迟消息取消订单
        sendDelayMessageCancelOrder(order.getOrderId());

        return CommonResult.success(orderItem, "下单成功");
    }

    /**
     * 支付成功后的回调
     */
    @Override
    public CommonResult paySuccess(Long orderId) {
        //修改订单支付状态
        OmsOrder order = new OmsOrder();
        order.setOrderId(orderId);
        order.setStatus(1);
        order.setPaymentTime(new Date());
        orderMapper.updateByPrimaryKeySelective(order);


        return CommonResult.success("支付成功");
    }

    /**
     * 自动取消超时订单
     */
    @Override
    public CommonResult cancelTimeOutOrder() {
        OmsOrderSetting orderSetting = orderSettingMapper.selectByPrimaryKey(1L);
        //查询超时、未支付的订单及订单详情
        List<OmsOrder> timeOutOrders = getTimeOutOrders(orderSetting.getNormalOrderOvertime());
        if (CollectionUtils.isEmpty(timeOutOrders)) {
            return CommonResult.failed("暂无超时订单");
        }
        //修改订单状态为交易取消
        updateOrderStatus(timeOutOrders, 4);

        for (OmsOrder timeOutOrder : timeOutOrders) {

            //解除订单商品库存锁定
            OmsOrderItemExample example = new OmsOrderItemExample();
            example.createCriteria().andOrderIdEqualTo(timeOutOrder.getOrderId());
            List<OmsOrderItem> omsOrderItemList =  orderItemMapper.selectByExample(example);
            releaseRentLock(omsOrderItemList);

        }
        return CommonResult.success("success");
    }

    /**
     * 取消单个超时订单
     */
    @Override
    public void cancelOrder(Long orderId) {
        //查询为付款的取消订单
        OmsOrderExample example = new OmsOrderExample();
        example.createCriteria().andOrderIdEqualTo(orderId).andStatusEqualTo(0);
        List<OmsOrder> cancelOrderList = orderMapper.selectByExample(example);
        if (CollectionUtils.isEmpty(cancelOrderList)) {
            return;
        }
        OmsOrder cancelOrder = cancelOrderList.get(0);
        if (cancelOrder != null) {
            //修改订单状态为取消
            cancelOrder.setStatus(5);
            orderMapper.updateByPrimaryKeySelective(cancelOrder);
            OmsOrderItemExample orderItemExample = new OmsOrderItemExample();
            orderItemExample.createCriteria().andOrderIdEqualTo(orderId);
            List<OmsOrderItem> orderItemList = orderItemMapper.selectByExample(orderItemExample);

        }
    }

    /**
     * 发送延迟消息取消订单
     */
    @Override
    public void sendDelayMessageCancelOrder(Long orderId) {
        //获取订单超时时间
        OmsOrderSetting orderSetting = orderSettingMapper.selectByPrimaryKey(1L);
        long delayTimes = orderSetting.getNormalOrderOvertime() * 60 * 1000;
//        long delayTimes =  60 * 1000;
        //发送延迟消息
        cancelOrderSender.sendMessage(orderId, delayTimes);
    }


    @Override
    public CommonResult getBuyerList(Long userId) {
        List<OrderReturnParam> orderReturnParamList = orderReturnParamDao.getBuyerOrderList(userId);

        return CommonResult.success(orderReturnParamList);
    }

    /**
     * 生成18位订单编号:8位日期+2位支付方式+6位以上自增id
     */
    private String generateOrderSn(OmsOrder order) {
        StringBuilder sb = new StringBuilder();
        String date = new SimpleDateFormat("yyyyMMdd").format(new Date());
        String key = REDIS_KEY_PREFIX_ORDER_ID + date;
        Long increment = redisService.increment(key, 1);
        sb.append(date);
        sb.append(String.format("%02d", order.getPayType()));
        String incrementStr = increment.toString();
        if (incrementStr.length() <= 6) {
            sb.append(String.format("%06d", increment));
        } else {
            sb.append(incrementStr);
        }
        return sb.toString();
    }
    /**
     * 锁定下单商品
     */
    private void lockStock(OmsOrderItem item) {

        pmsProductFeignApi.lockProduct(item.getProductId());
    }
    /**
     * 锁定下单商品
     */
    private void releaseRentLock(List<OmsOrderItem> orderItemList) {
        for(OmsOrderItem orderItem: orderItemList){
            pmsProductFeignApi.releaseRentLock(orderItem.getProductId());
        }
    }


    private List<OmsOrder> getTimeOutOrders(Integer minute){
        long currentTime = System.currentTimeMillis() ;
        currentTime -= minute *60*1000;
        Date date=new Date(currentTime);
        OmsOrderExample example = new OmsOrderExample();
        example.createCriteria().andCreateTimeLessThan(date);
        List<OmsOrder> orderList = orderMapper.selectByExample(example);
        return orderList;
    }

    private void updateOrderStatus(List<OmsOrder>orderList, Integer orderStatus){
        for(OmsOrder order: orderList){
            order.setStatus(orderStatus);
            orderMapper.updateByPrimaryKey(order);
        }
    }

    private OmsOrder insertOrder(OrderParam orderParam) {
        UmsMember currentMember = memberFeignApi.getByUserId(orderParam.getBuyUserId()).getData();

        //根据商品合计、运费、积分计算应付金额
        OmsOrder order = new OmsOrder();

        //转化为订单信息并插入数据库
        order.setBuyUserId(orderParam.getBuyUserId());
        order.setCreateTime(new Date());
        order.setBuyerUsername(orderParam.getBuyerUsername());
        //支付方式：0->未支付；1->支付宝；2->微信
        order.setPayType(orderParam.getPayType());
        order.setNote(orderParam.getNote());

        //订单状态：0->待付款；1->待发货；2->已发货；3->已完成；4->已关闭；5->无效订单
        order.setStatus(0);

        //收货人信息：id,姓名、电话、邮编、地址
        Long addressId = orderParam.getMemberReceiveAddressId();
        UmsMemberReceiveAddress address = memberReceiveAddressFeignApi.getItem(addressId).getData();
        order.setSellUserId(orderParam.getSellUserId());
        order.setSellerUsername(orderParam.getSellerUsername());
        order.setReceiverName(address.getName());
        order.setReceiverPhone(address.getTel());
        order.setReceiverProvince(address.getProvince());
        order.setReceiverCity(address.getCity());
        order.setReceiverCounty(address.getCounty());
        order.setReceiverDetailAddress(address.getAddress());
        //0->未确认；1->已确认
        order.setConfirmStatus(0);

        //生成订单号
        order.setOrderSn(generateOrderSn(order));

        //插入order表和order_item表
        orderMapper.insert(order);

        log.warn(order.toString());

        return order;
    }



}